<?php

/**
 * MySQL Class
 *
 * Driver for working with DataBases on MySQL
 */
class MySQL {
	
	private $_connect = false;
	
	function __construct($params){
		$this->_connect = mysql_connect($params['host'],$params['username'],$params['password']);
		mysql_select_db($params['db']);
		mysql_query("set charset ".$params['charset']);
	}

	public function close() { mysql_close($this->_connect); }

	public function sendQuery($query) {
		if ($this->getQ($query)){
			if (strpos($query,"insert") === 0){
				return mysql_insert_id();
			} else {
				return true;
			}
		}
		
		return false;
	}

	public function getQ($query){

		if ($result = mysql_query($query)){
			return $result;
		} else {
			$trace = debug_backtrace();
			$level = 0;
			if (in_array($trace[1]['function'], array('getCell', 'getRow', 'getColumn', 'getTable')))
				$level = 1;
			$message =
				'<p><strong>MySQL error</strong> in file <strong>'.$trace[$level]['file'].'</strong>'.
				" at line <strong>" .$trace[$level]['line']."</strong>
				(function <strong>" . $trace[$level]['function'] ."</strong>):<br/>"
				."\n<span style='color:blue'>".mysql_error()."</span>\n\n<pre>$query</pre></p>";
			die($message);
		}
	}

	public function getCell($query,$row_name=0){
		$cell = FALSE;
		if ($result = $this->getQ($query) AND $row = mysql_fetch_array($result)){
			$cell = $row[$row_name];
		}
		
		return $cell;
	}

	public function getRow($query){
		$row = array();
		if ($result = $this->getQ($query)){
			$row = mysql_fetch_assoc($result);
		}
		
		return $row;
	}

	public function getColumn($query, $makehash = FALSE){
		$data = array();
		$result = $this->getQ($query);
		if (!$makehash) {
			while ($row = mysql_fetch_row($result)) {
				$data[] = $row[0];
			}
		} else {
			while ($row = mysql_fetch_array($result)){
				$data[$row{0}] = $row[$makehash];
			}
		}
		
		return $data;
	}

	public function getTable($query, $keycol = NULL){
		$data = array();
		$result = $this->getQ($query);
		if (is_null($keycol)) {
			while ($row = mysql_fetch_assoc($result)){
				$data[] = $row;
			}
		} else {
			while ($row = mysql_fetch_assoc($result)){
				$data[$row{$keycol}] = $row;
			}
		}
		
		return $data;
	}
}

?>